<?php

namespace app\api\service;

use app\model\Applet;
use app\model\Concern;
use app\model\Admin;
use app\model\UserWechatSubscribeConfig;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Db;
use app\model\Videos;
use app\model\Other;
use app\model\BingeWatch;
use app\model\User;
use app\model\Link;
use app\common\Error;
use app\model\Money;
use app\model\Company;
use think\facade\Cache;
use app\model\SetFollowDrama;
use app\model\OfficialAccounts;
use app\model\Records;
use app\model\PayRecord;
use app\common\Common;
use app\model\UserLove;
use app\model\VideoDetails;
use app\model\Proposal;
use app\api\service\TiktokService;
use app\model\TemplateMessgeSubscribe;
use think\facade\Log;
use app\model\ResponsibilityPerson;
/**
 * 用户服务类
 */
class UserService
{
    private $concernModel;
    private $adminModel;
    private $videosModel;
    private $otherModel;
    private $bingeWatchModel;
    private $userModel;
    private $moneyModel;
    private $officialAccountsModel;
    private $setFollowDramaModel;
    private $recordsModel;
    private $payRecordModel;
    private $userLoveModel;
    private $videoDetailsModel;
    private $proposalModel;
    private $service;
    private $templateMessgeSubscribeModel;
    private $responsibilityPersonModel;
    private $linkModel;
    private $companyModel;
   /**
     * @var Redis
     */
    private $redis;
    public function __construct(
        Concern $concernModel,
        Admin $adminModel,
        Videos $videosModel,
        Other $otherModel,
        BingeWatch $bingeWatchModel,
        User $userModel,
        Money $moneyModel,
        SetFollowDrama $setFollowDramaModel,
        OfficialAccounts $officialAccountsModel,
        Records $recordsModel,
        PayRecord $payRecordModel,
        UserLove $userLoveModel,
        VideoDetails $videoDetailsModel,
        Proposal $proposalModel,
        TiktokService $service,
        TemplateMessgeSubscribe $templateMessgeSubscribeModel,
        ResponsibilityPerson $responsibilityPersonModel,
        Link $linkModel,
        Company $companyModel
    ) {
        $this->concernModel = $concernModel;
        $this->adminModel = $adminModel;
        $this->videosModel = $videosModel;
        $this->otherModel = $otherModel;
        $this->bingeWatchModel = $bingeWatchModel;
        $this->userModel = $userModel;
        $this->moneyModel = $moneyModel;
        $this->setFollowDramaModel = $setFollowDramaModel;
        $this->officialAccountsModel = $officialAccountsModel;
        $this->recordsModel = $recordsModel;
        $this->payRecordModel = $payRecordModel;
        $this->userLoveModel = $userLoveModel;
        $this->videoDetailsModel = $videoDetailsModel;
        $this->proposalModel = $proposalModel;
        $this->service = $service;
        $this->redis = Cache::store('redis')->handler();
        $this->templateMessgeSubscribeModel = $templateMessgeSubscribeModel;
        $this->responsibilityPersonModel=$responsibilityPersonModel;
        $this->linkModel=$linkModel;
        $this->companyModel=$companyModel;
    }

    /**
     * 获取发布者的详细信息
     * 
     * @dateTime 2022/09/13
     * @author zhixiang0215@126.com
     * @param int adminId
     * @param int uid
     * @return array
     */
    public function getUserDetailInfo($params, $uid)
    {
        $adminId = $params['admin_id'];
        $videoId = $params['video_id'];
        $data = $this->adminModel->getInfoById(intval($adminId), 'id, name, profile_photo, fans_count, introduce');
        $appId = $params['app_id'] ?? 1;
        //增加判断当前链接是否属于分销商
        $is_automatic= $this->getIsAutomatic($uid);
        $where = [
            ['uid', '=', $adminId],
            ['is_delete', '=', 0],
            ['is_shelves', '=', 1],
            ['id', '<>', $videoId]
        ];
        //start-----------by zengyang  2023-09-06  区分原始剧和复制剧
        //自投appid,展示自投剧
      //增加一个判断当前链接是否是分销商
      if($is_automatic != 2){
        $where[] = ['is_copy','=',(int)$is_automatic];
    }else{
        if(in_array($appId, config('enum.my_appid'))){
            $where[] = ['is_copy','=',0];
        }else{
            $where[] = ['is_copy','=',1];
        }
    }
        //end

        $fields = 'id, video_type_id, name, label, title_label, cover_img, is_free, give_count, update_sort,original_id';
        $order = 'is_recommended desc, give_count desc, sort desc';

        $videoData = $this->videosModel->getDataByWhere($where, $fields, $order, 4);
        //start-----------by zengyang  2023-09-06  区分原始剧和复制剧
        //不是自投appid,展示复制剧
        if(!in_array($appId, config('enum.my_appid'))||$is_automatic == 1) {
            foreach($videoData as $k_d => $v_d) {
                $original = $this->videosModel->getInfoById($videoData[$k_d]['original_id']);
                if(!empty($original)) {
                    $videoData[$k_d]['name'] = $original['name'];//用原始剧的名称替换复制剧的名称
                }
            }
        }
        //end


        $redis = Cache::store('redis')->handler();
        $redis->select(7);

        if ($videoData) {
            $videoIds = array_column($videoData, 'id');
            // $records = $this->recordsModel->getDataByWhere(['video_id' => $videoIds, 'uid' => $uid], 'video_id, video_detail_id');
            // $recordData = array_column($records, 'video_detail_id', 'video_id');

            $watchKey = config('redis_key.user_watch_record').$uid;
            $watchData = $redis->get($watchKey);
            if ($watchData) {
                $recordData = json_decode($watchData, true);
            } else {
                $watchData = $this->recordsModel->getDataByWhere(['uid' => $uid], 'video_detail_id, video_id');
                $recordData = array_column($watchData, 'video_detail_id', 'video_id');
                $redis->set($watchKey, json_encode($recordData), config('redis_key.user_watch_record_expire'));
            }

            foreach ($videoData as $key => $item) {
                $videoData[$key]['video_detail_id'] = empty($recordData[$item['id']]) ? 1 : $recordData[$item['id']];
            }
        }

        // 是否关注
        $isConcern = $this->concernModel->getInfo(['admin_id' => $adminId, 'uid' => $uid], 'id');
        $data['concern'] = false;
        if ($isConcern) {
            $data['concern'] = true;
        }

        $otherData = $this->otherModel->getInfoByAdminUid($adminId, 'video_id');

        if ($otherData) {
            $videoIdsArray = explode(',', $otherData['video_id']);
            $videoIds = [];
            foreach ($videoIdsArray as $value) {
                if ($value != $videoId) {
                    $videoIds[] = $value;
                }
            }

            $otherVideoData = $this->videosModel->getDataByWhere(['id' => $videoIds], $fields);
            //start-----------by zengyang  2023-09-06  区分原始剧和复制剧
            //不是自投appid,展示复制剧
            if(!in_array($appId, config('enum.my_appid'))||$is_automatic == 1) {
                foreach($otherVideoData as $k_d_other => $v_d_other) {
                    $original = $this->videosModel->getInfoById($otherVideoData[$k_d_other]['original_id']);
                    if(!empty($original)) {
                        $otherVideoData[$k_d_other]['name'] = $original['name'];//用原始剧的名称替换复制剧的名称
                    } else {
                        unset($otherVideoData[$k_d_other]);
                    }
                }
            }
            //end

            $bingeWatchData = $this->bingeWatchModel->getDataByWhere(['uid' => $uid, 'video_id' => $videoIds], 'video_id, sort');
            $bingeWatch = array_column($bingeWatchData, 'sort', 'video_id');

            // $records = $this->recordsModel->getDataByWhere(['video_id' => $videoIds, 'uid' => $uid], 'video_id, video_detail_id');
            // $recordData = array_column($records, 'video_detail_id', 'video_id');

            $watchKey = config('redis_key.user_watch_record').$uid;
            $watchData = $redis->get($watchKey);
            if ($watchData) {
                $recordData = json_decode($watchData, true);
            } else {
                $watchData = $this->recordsModel->getDataByWhere(['uid' => $uid], 'video_detail_id, video_id');
                $recordData = array_column($watchData, 'video_detail_id', 'video_id');
                $redis->set($watchKey, json_encode($recordData), config('redis_key.user_watch_record_expire'));
            }

            foreach ($otherVideoData as $key => $item) {
                $otherVideoData[$key]['chase'] = empty($bingeWatch[$item['id']]) ? false : true;
                // 更新到第多少集
                $otherVideoData[$key]['sort'] = $item['update_sort'];
                // 上次观看到哪
                $otherVideoData[$key]['video_detail_id'] = empty($recordData[$item['id']]) ? 1 : $recordData[$item['id']];
            }
        }

        $data['recommended_video_data'] = $videoData;
        $data['other_list'] = $otherData ? $otherVideoData : [];

        // 获取总点赞次数
        $giveCountData = $this->videosModel->getGiveCount(['uid' => $adminId]);
        $count = 0;
        foreach ($giveCountData as $value) {
            $count += $value['give_count'];
        }
        $data['count'] = $count;

        return $data;
    }

    /**
     * 查看发布者的全部视频
     * 
     * @dateTime 2022/09/13
     * @author zhixiang0215@126.com
     * @param array params
     * @return json
     */
    public function getAllVideoData($params, $uid)
    {
        $adminId = intval($params['admin_id']);
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;

        $where = [
            'uid' => $adminId,
            'is_delete' => 0,
            'is_shelves' => 1
        ];

        $fields = 'id, video_type_id, name, label, title_label, cover_img, is_free, give_count';
        $order = 'is_recommended desc, give_count desc, sort desc';

        $data = $this->videosModel->getPagingDataByWhere($where, $page, $limit, $fields, $order);

        if ($data['data']) {
            $videoIds = array_column($data['data'], 'id');
            // $recordData = $this->recordsModel->getDataByWhere(['uid' => $uid, 'video_id' => $videoIds], 'video_id, video_detail_id');
            // $record = array_column($recordData, 'video_detail_id', 'video_id');

            $redis = Cache::store('redis')->handler();
            $redis->select(7);
            $watchKey = config('redis_key.user_watch_record').$uid;
            $watchData = $redis->get($watchKey);
            if ($watchData) {
                $record = json_decode($watchData, true);
            } else {
                $watchData = $this->recordsModel->getDataByWhere(['uid' => $uid], 'video_detail_id, video_id');
                $record = array_column($watchData, 'video_detail_id', 'video_id');
                $redis->set($watchKey, json_encode($record), config('redis_key.user_watch_record_expire'));
            }

            foreach ($data['data'] as $key => $value) {
                $data['data'][$key]['video_detail_id'] = empty($record[$value['id']]) ? 0 : $record[$value['id']];
            }
        }

        // 发布者信息
        $userInfo = $this->adminModel->getInfoById($adminId, 'id, name, profile_photo, fans_count, introduce');
        $data['user_info'] = $userInfo;

        return $data;
    }

    /**
     * 粉丝修改(粉丝新增或删除)
     * 
     * @dateTime 2022/09/06
     * @author zhixiang0215@126.com
     * @param array params
     * @param int uid
     * @return bool
     */
    public function fansEdit($params, $uid)
    {
        $adminId = $params['admin_id'];
        $where = [
            'admin_id' => $adminId,
            'uid' => $uid
        ];
        $data = $this->concernModel->getInfo($where, 'id');

        Db::startTrans();
        try {
            if ($params['type'] == 1) {
                // type为1是新增
                $incBool = Db::name('admin')->where(['id' => $adminId])->inc('fans_count', 1)->update();

                if (!$incBool) {
                    Db::rollback();
                    return false;
                }

                if (!$data) {
                    $bool = Db::name('concern')->insert([
                        'uid'         => $uid,
                        'admin_id'    => $adminId,
                        'created_at' => time(),
                        'updated_at' => time()
                    ]);

                    if (!$bool) {
                        Db::rollback();
                        return false;
                    }
                }

            } else {
                // type是2为减少
                $decBool = Db::name('admin')->where(['id' => $adminId])->dec('fans_count', 1)->update();

                if (!$decBool) {
                    Db::rollback();
                    return false;
                }

                if ($data) {
                    $bool = Db::name('concern')->where(['id' => $data['id']])->delete();
                    if (!$bool) {
                        Db::rollback();
                        return false;
                    }
                }
            }

            Db::commit();
            return true;
        } catch (\Exception $e) {
            Log::record('粉丝修改fansEdit:'.$e->getMessage());
            Db::rollback();
            return false;
        }
    }

    /**
     * 获取书币数量
     * 
     * @dateTime 2022/09/06
     * @author zhixiang0215@126.com
     * @param int uid
     * @return array
     */
    public function getUserBookCurrency($uid, $params)
    {
        $data = $this->userModel->getInfoById($uid, 'is_members, expiration_time, money, first_charge_date');
        $data['exp_time'] = 0;
        if ($data && $data['is_members'] == 1) {
            if (time() > $data['expiration_time']) {
                $data['is_members'] = 0;
            }else{
                $exp_time=$data['expiration_time']-time();
                $data['exp_time'] =  floor($exp_time / (60 * 60 * 24));
            }
            $data['expiration_time'] = date('Y-m-d', $data['expiration_time']);
        }
        $data['is_money'] = 0;

        /**
         * start
         * 判断会员用户是否达到剧设置金额免费观看的层次
         */
        if(!empty($params['video_id']) && $data['is_members'] == 1) {
            $paycount = $this->payRecordModel->getInfo(['uid' => $uid,'status' => 1,'refund_status' => 0], 'type,total_fee,activation_time,pay_time');
            if(!empty($paycount)) {
                //将用户的未过期的会员都加起来
                $money = 0;
                $time = time();
                foreach ($paycount as $key => $value) {
                    $start_time = $value['pay_time'];
                    switch ($value['type']) {
                        case 2:
                            # 年卡
                            $end_time = $start_time + (365 * 24 * 60 * 60);
                            break;
                        case 3:
                            # 半年卡
                            $end_time = $start_time + (180 * 24 * 60 * 60);
                            break;
                        case 4:
                            # 季卡
                            $end_time = $start_time + (90 * 24 * 60 * 60);
                            break;
                        case 5:
                            # 60天卡
                            $end_time = $start_time + (60 * 24 * 60 * 60);
                            break;
                        case 6:
                            # 30卡
                            $end_time = $start_time + (30 * 24 * 60 * 60);
                            break;
                        case 7:
                            # 10卡
                            $end_time = $start_time + (10 * 24 * 60 * 60);
                            break;
                        case 8:
                            # 7卡
                            $end_time = $start_time + (7 * 24 * 60 * 60);
                            break;
                        case 11:
                            # 3卡
                            $end_time = $start_time + (3 * 24 * 60 * 60);
                            break;
                        case 15:
                            # 1卡
                            $end_time = $start_time + (1 * 24 * 60 * 60);
                            break;
                        default:
                            # 不计算...
                            $end_time = 0;
                            break;
                    }
                    if($end_time != 0 && $end_time > $time) {
                        $money += $value['total_fee'];
                    }
                }
                $video = $this->videosModel->getInfoById($params['video_id'], 'is_money,launch_start_time');

                if(!empty($video) && $video['is_money'] != 0 && $money < $video['is_money']) {
                    //还需要判断用户不是从挂载进来
                    // $redis = Cache::store('redis')->handler();
                    // $redis->select(8);
                    // $mountKey = config('redis_key.api.user_login_mount_key') . $uid;
                    // $mount = $redis->get($mountKey);

                    //只对投放时间十天内的才进行当前判断
                    $launch_end_time = $video['launch_start_time'] + (10 * 24 * 60 * 60);
                    if($launch_end_time > $time ) {
                        $data['is_money'] = 1;
                    }
                }
            }
        }
        /**
         * 判断结束
         * end
         */

        // $moneyData = $this->moneyModel->getDataByWhere(['is_common' => 1, 'type' => 2], 'name, label, display_object, original_currency, recharge_price, send_currency, sum_currency, send_title');

        // if (!empty($moneyData[0])) {
        //     $data['member_title'] = $moneyData[0]['recharge_price'].'元包年，开通后尊享6项特权';
        // } else {
        //     $data['member_title'] = '365元包年，开通后尊享6项特权';
        // }

        return $data;
    }

    // 用户签到
    public function userSign($uid)
    {
        $data = $this->userModel->getInfoById($uid, 'id, sign_time, sign_day, money, official_account_id,platform,open_id, mobile_system');

        if (!$data) {
            return ['message' => Error::PLEASE_LOGIN_FIRST];
        }
        // 
        $currentSignTime = strtotime(date('Y-m-d', time()));
        $lastSignTime = strtotime(date('Y-m-d', $data['sign_time']));

        if ($currentSignTime == $lastSignTime) {
            return ['message' => Error::SIGNED_IN_TODAY];
        }

        $dayNum = ($currentSignTime - $lastSignTime) / 86400;

        if ($dayNum == 1) {
            // 连续签到
            if ($data['sign_day'] == 0 || $data['sign_day'] == 7) {
                // 第1天签到或者签到已满7天
                $money = 35;
                $signDay = 1;
            } else if ($data['sign_day'] == 1) {
                // 连续第2天签到
                $money = 40;
                $signDay = 2;
            } else if ($data['sign_day'] == 2) {
                // 连续第3天签到
                $money = 45;
                $signDay = 3;
            } else if ($data['sign_day'] == 3) {
                // 连续第4天签到
                $money = 50;
                $signDay = 4;
            } else if ($data['sign_day'] == 4) {
                // 连续第5天签到
                $money = 55;
                $signDay = 5;
            } else if ($data['sign_day'] == 5) {
                // 连续第6天签到
                $money = 60;
                $signDay = 6;
            } else if ($data['sign_day'] == 6) {
                // 连续第7天签到
                $money = 70;
                $signDay = 7;
            }
        } else {
            $money = 35;
            $signDay = 1;
        }
        // 增加后的K币
        $userMoney = $data['money'] + $money;
        // 更新数据
        $saveData = [
            'id' => $uid,
            'money' => $userMoney,
            'sign_day' => $signDay,
            'sign_time' => time(),
            'updated_at' => time()
        ];

        // 添加记录到pay_record表
        $payRecordData = [
            'uid' => $uid,
            'name' => '签到',
            'type' => 9,
            'number' => $money,
            'status' => 1,
            'pay_time' => time(),
            'consume_date' => intval(date('Ymd')),
            'consume_month' => intval(date('Ym')),
            'created_at' => time(),
            'official_account_id' => $data['official_account_id'],
            'total_fee' => '0.00',
            'device_type' => WechatService::getDeviceType($data['mobile_system'] ?? ''),
        ];
        $id = $this->payRecordModel->edit($payRecordData);

        $bool = $this->userModel->edit($saveData);
        //抖音小程序签到通知
        if($data['platform'] == 2) {
            $getAppletInfo  = $this->service->getAppletInfo($uid);
            $arr    =[
                'access_token'=> $this->service->getAccessToken($uid),
                'app_id'      => $getAppletInfo['app_id'],
                'tpl_id'      => $getAppletInfo['template_id'],
                'open_id'     => $data['open_id'],
                'data'        =>[
                    '签到名称'=>'签到',
                    '签列奖励'=>'K币奖励',
                    '温馨提示'=>'此K币可用来看剧消费'
                ],
                'page'      =>'/pages/index/index'
            ];
            $this->service->notificationMessage($arr);
        }
        return $bool ? ['user_money' => $userMoney, 'add_money' => $money, 'sign_day' => $signDay] : [];
    }

    /**
     * 用户广告签到
     * @param $uid
     * @return array
     */
    public function adSign($uid)
    {
        $userInfo = $this->userModel->getInfoById($uid, 'id, sign_time, sign_day, money, platform, official_account_id, mobile_system');
        if (!$userInfo) {
            return ['code' => Error::FAIL_CODE, 'message' => Error::PLEASE_LOGIN_FIRST];
        }

        $start_time = strtotime(date('Y-m-d'));
        $end_time = strtotime(date('Y-m-d 23:59:59'));
        if ($userInfo['sign_time'] > $end_time || $userInfo['sign_time'] < $start_time) {
            return ['code' => Error::FAIL_CODE, 'message' => '请先完成签到'];
        }

        $payRecordCount = $this->payRecordModel->getCount([
            'uid' => $uid,
            'type' => Money::TYPE_AD_SIGN,
            'status' => 1,
            ['pay_time','between', [$start_time, $end_time]]
        ]);
        if ($payRecordCount) {
            return ['code' => Error::FAIL_CODE, 'message' => '今天已领取奖励'];
        }

        switch ($userInfo['sign_day']) {
            case 2:
                $money = 40;
                break;
            case 3:
                $money = 45;
                break;
            case 4:
                $money = 50;
                break;
            case 5:
                $money = 55;
                break;
            case 6:
                $money = 60;
                break;
            case 7:
                $money = 70;
                break;
            default:
                $money = 35;
                break;
        }

        $bool = $this->payRecordModel->edit([
            'uid' => $uid,
            'name' => '广告奖励',
            'type' => Money::TYPE_AD_SIGN,
            'number' => $money,
            'status' => 1,
            'pay_time' => time(),
            'consume_date' => intval(date('Ymd')),
            'consume_month' => intval(date('Ym')),
            'created_at' => time(),
            'official_account_id' => $userInfo['official_account_id'],
            'total_fee' => '0.00',
            'device_type' => WechatService::getDeviceType($userInfo['mobile_system'] ?? ''),
        ]);

        if ($bool) {
            // 增加后的K币
            $userMoney = round($userInfo['money'] + $money);
            $this->userModel->edit([
                'id' => $uid,
                'money' => $userMoney,
                'updated_at' => time()
            ]);
            return [
                'code' => Error::SUCCESS_CODE,
                'message' => '',
                'data' => ['user_money' => $userMoney, 'add_money' => $money]
            ];
        }
        return ['code' => Error::FAIL_CODE, 'message' => Error::FAIL_MESSAGE];
    }

    // 获取关注列表
    public function getConcernList($uid)
    {
        $adminIdData = $this->concernModel->getDataByWhere(['uid' => $uid], 'admin_id');
        $adminIds = array_column($adminIdData, 'admin_id');

        $data = $this->adminModel->getDataByWhere(['id' => $adminIds], 'id, name, profile_photo, fans_count, introduce');

        return $data;
    }

    // 我的喜欢列表
    public function getLoveList($params, $uid)
    {
        $page = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 10;

        $data = $this->userLoveModel->getPagingDataByWhere(['uid' => $uid], $page, $limit, 'id, video_id, video_detail_id');
        $videoIds = array_column($data['data'], 'video_id');
        $videoDetailIds = array_column($data['data'], 'video_detail_id');

        $videoData = $this->videosModel->getDataByIds($videoIds, 'id, name, cover_img');
        $video = array_column($videoData, NULL, 'id');

        $detailData = $this->videoDetailsModel->getInfoByIds($videoDetailIds, 'id, sort, give_count');
        $detail = array_column($detailData, NULL, 'id');

        if ($data['data']) {
            foreach ($data['data'] as $key => $item) {
                $data['data'][$key]['name'] = $video[$item['video_id']]['name'];
                $data['data'][$key]['cover_img'] = $video[$item['video_id']]['cover_img'];

                $data['data'][$key]['sort'] = $detail[$item['video_detail_id']]['sort'];
                $data['data'][$key]['give_count'] = $detail[$item['video_detail_id']]['give_count'];
            }
        }
        return $data;
    }

    // 判断用户是否关注公众号
    public function userIsFollowOfficialAccount($params, $uid)
    {
        $redis = Cache::store('redis')->handler();
        $key = config('redis_key.api.user_login');
        $userInfo = $redis->get($key . $uid);
        $userInfo = json_decode($userInfo, true);

        $data = [];
        $videoId = $params['video_id'];
        // 提醒用户关注公众号
        $data['is_remind_user_follow'] = 0;
        $data['follow_official_accounts_url'] = '';
        $data['follow_official_accounts_sort'] = 0;
        if (empty($userInfo['status'])) {
            $setFollowDramaData = $this->setFollowDramaModel->getInfoByWhere(['official_account_id' => $userInfo['official_account_id'], 'video_id' => $videoId], 'follow_sort');

            if ($setFollowDramaData) {
                $data['follow_official_accounts_sort'] = $setFollowDramaData['follow_sort'];
                // 获取需要关注公众号信息
                $officialAccountData = $this->officialAccountsModel->getInfoById($userInfo['official_account_id'], 'id, app_id, app_secret');
                $data['is_remind_user_follow'] = 1;
                // 获取生成关注公众号的二维码链接
                // file_put_contents('./public_login.txt', date("Y-m-d H:i:s").' ：'.$uid.' ; '.PHP_EOL, FILE_APPEND);
                $url = Common::getOfficialAccountFollowQrcodeUrl($officialAccountData, $uid);

                if (!$url) {
                    return [];
                }

                $qrcodeUrl = Common::createQrcode($url, 'uploads/qrcode/'.$uid.'.png', 8);
                if (!$qrcodeUrl) {
                    return [];
                }

                $data['follow_official_accounts_url'] = $qrcodeUrl;
            }
        }

        return $data;
    }

    // 获取用户签到数据
    public function getUserSignData($param, $uid)
    {
        $app_id = $param['app_id'] ?? '';
        $ad_id = '';
        $is_open_ad = 0;
        if (!empty($app_id)) {
            $appletData = Applet::field('id,is_open_ad,ad_id')->where(['app_id' => $app_id])->find();
            if ($appletData) {
                $appletData = $appletData->toArray();
            }
            $is_open_ad = $appletData ? $appletData['is_open_ad'] : 0;
            $ad_id = Applet::getAdIdByScene($appletData, Applet::AD_SCENE_2);
        }

        $data = $this->userModel->getInfoById($uid, 'sign_time, sign_day');
        if (empty($data['sign_time'])) {
            // 未使用过签到
            return [
                'ad_id' => $ad_id,
                'is_open_ad' => $is_open_ad,
                'today_is_sign' => 0,
                'continuous_sign_days' => 0,
            ];
        }

        $lastSignTime = strtotime(date('Y-m-d', $data['sign_time']). ' 23:59:59');
        $currentTime = strtotime(date('Y-m-d', time()). ' 23:59:59');

        if ($currentTime - $lastSignTime >= 172800) {
            // 昨天未签到
            return [
                'ad_id' => $ad_id,
                'is_open_ad' => $is_open_ad,
                'today_is_sign' => 0,
                'continuous_sign_days' => 0,
            ];
        }

        if ($currentTime - $lastSignTime >= 86400) {
            // 昨天签过到 今天未签到
            return [
                'ad_id' => $ad_id,
                'is_open_ad' => $is_open_ad,
                'today_is_sign' => 0,
                'continuous_sign_days' => $data['sign_day'],
            ];
        }
        // 今天已签到
        return [
            'ad_id' => $ad_id,
            'is_open_ad' => $is_open_ad,
            'today_is_sign' => 1,
            'continuous_sign_days' => $data['sign_day'],
        ];
    }

    // 获取用户投诉建议
    public function getUserProposal($params, $uid)
    {
        $params['uid'] = $uid;
        $params['created_at'] = time();
        if (!empty($params['images'])) {
            $params['images'] = json_encode($params['images']);
        }
        $bool = $this->proposalModel->edit($params);
        return $bool ? true : false;
    }

    // 添加用户订阅消息
    public function addUserSubscribeMessage($params, $uid)
    {
        $params['created_at'] = time();
        $params['uid'] = $uid;
        $data = $this->userModel->getInfoById($uid, 'open_id');

        $params['open_id'] = $data['open_id'];
        $id = $this->templateMessgeSubscribeModel->edit($params);

        return $id;
    }

    /**
     * 添加用户微信订阅消息
     * @param $params
     * @param $userId
     * @return bool
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function addUserWechatSubscribeMessage($params, $userId): bool
    {
        $appletId = Applet::where('app_id',$params['app_id'])->value('id') ?? '';
        $params['applet_id'] = $appletId;
        $info = UserWechatSubscribeConfig::where([
            'user_id' => $userId,
            'applet_id' => $appletId,
        ])->find();
        $subscribeConfig = $params['subscribe_config'] ?? [];
        if (!$info) {
            $info = new UserWechatSubscribeConfig();
            $info->user_id = $userId;
            $info->applet_id = $appletId;
            $subscribeConfigData = [];
        }else{
            $subscribeConfigData = collect($info->subscribe_config)->toArray();
        }
        // 合并两个数组
        $mergedSubscribeConfig = array_merge($subscribeConfigData,$subscribeConfig);
        $mergedSubscribeConfig = array_values(array_reduce($mergedSubscribeConfig, function ($result, $item) {
            $result[$item['template_id']] = $item;
            return $result;
        }, []));
        $info->subscribe_config = $mergedSubscribeConfig;
        return $info->save();
    }
        /**
     * 判断是否为分销商推广链接
     *
     * @param [type] $uid  用户id
     * @return int
     */
    public function getIsAutomatic($uid){
        $linkIdKey = config('redis_key.api.user_login');
        $this->redis->select(8);
        $linkId=json_decode($this->redis->get($linkIdKey . $uid),true);
        if (!empty($linkId['link_id'])) {
            $linklist=$this->linkModel->getInfoByWhere(['id'=>$linkId['link_id']],'responsibility_person_id');
            
            if (!empty($linklist)) {
                $responsibility = $this->responsibilityPersonModel->getInfoByWhere(['id' => $linklist['responsibility_person_id']], 'company_id');
                if(!empty($responsibility)) {
                    $data = $this->companyModel->getInfoById($responsibility['company_id'], 'is_distributor');
                    return isset($data['is_distributor']) ? (int)$data['is_distributor'] : 2;
                }
            }
        }
        return 2;
    }
}